package com.crm.system.service.impl.taskManager;

import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.taskManager.TaskUsersQO;
import com.crm.model.qo.taskManager.TaskUserQO;
import com.crm.model.vo.taskManager.TaskUserVO;
import com.crm.service.taskManager.TaskUserDbService;
import com.crm.system.service.taskManager.TaskUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author renshaorong
 * @Date 2021/4/26
 */
@Service
public class TaskUserServiceImpl implements TaskUserService {

    @Autowired
    private TaskUserDbService taskUserDbService;

    /**
     * 选中任务信息后获取任务分配人员
     * @param pageIndex
     * @param pageSize
     * @param sortName
     * @param sortOrder
     * @param taskUserQO
     * @return
     */
    @Override
    public DhPageInfo<TaskUserVO> getTaskUserByTaskId(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, TaskUserQO taskUserQO) {
        if(taskUserQO == null){
            taskUserQO = new TaskUserQO();
        }
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //增加删除状态查询条件(0:正常;1:已删除)
        taskUserQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
        taskUserQO.setAccountId(((UserAccount) SecurityUtils.getSubject().getPrincipal()).getAccountId());

        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "createTm":
                {
                    order.append("a.create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }

        List<TaskUserVO> taskUserList  = taskUserDbService.getTaskUserByTaskId(taskUserQO, order.toString());
        PageInfo<TaskUserVO> pageInfo = new PageInfo<TaskUserVO>(taskUserList);
        return new DhPageInfo<TaskUserVO>(pageInfo, taskUserList);
    }

    /**
     * 保存分配
     * @param taskUsersQO
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public boolean saveTaskUser(TaskUsersQO taskUsersQO) {
        taskUsersQO.setCreatePeopleId(((UserAccount) SecurityUtils.getSubject().getPrincipal()).getAccountId());
        return taskUserDbService.inserts(taskUsersQO);
    }
}
